#!/bin/bash

set -o errexit
set -o nounset

# We need this script because Go doesn't support a nice/non-destructive way
# to check for modules tidyness: https://github.com/golang/go/issues/27005

function go_mod_changes() {
    git status go.mod --porcelain
}

changes="$(go_mod_changes)"

if [[ ! -z "${changes}" ]]
then
      echo "go.mod already has changes, this should be run with all go.mod changes commited"
      exit 1
fi

go mod tidy
changes="$(go_mod_changes)"

if [[ ! -z "${changes}" ]]
then
      echo "changes detected after tidying modules:"
      echo "${changes}"

      echo
      echo "undoing changes"
      git checkout go.mod
      exit 1
fi
